package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.jwt.AppJwtUtil;
import com.usian.common.contants.behavior.BehaviorConstants;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserService;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends BaseServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    ArticleFeign articleFeign;
    @Autowired
    ApUserFollowMapper follow;
    @Autowired
    ApUserFanMapper fan;
    @Autowired
    KafkaTemplate kafkaTemplate;
    @Override
    public ResponseResult login(LoginDto dto) {
        Map<String,Object> map = new HashMap<>();
        if (dto.getPhone()==null&&dto.getPhone()==null){
            map.put("token",AppJwtUtil.getToken(Long.valueOf(0)));
            return ResponseResult.okResult(map);
        }
        if (dto==null||dto.getPassword()==null||dto.getPhone()==null)return errorParam;
        ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (apUser==null)return notExit;
        if (apUser.getPassword().equals(DigestUtils.md5DigestAsHex((dto.getPassword()+apUser.getSalt()).getBytes()))){
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("apuser",apUser);
            Integer id = apUser.getId();
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            kafkaTemplate.send(BehaviorConstants.LOGIN_BEHAVIOR_TOPIC, JSON.toJSONString(apUser.getId()));
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
    }

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        if (ThreadLocalUtils.getUser()==0)return notLogin;
        if (dto==null||dto.getAuthorId()==null||dto.getOperation()==null)return errorParam;
        //查询作者信息
        ApAuthor author = articleFeign.findByAuthorId(dto.getAuthorId());
        //查询当前登录用户信息
        ApUser apUser = getById(ThreadLocalUtils.getUser());
        //关注
        if (dto.getOperation()==0){
            ApUserFollow apUserFollow = follow.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, author.getUserId()));
            if (apUserFollow==null) saveFollow(apUser,author);
            ApUserFan apUserFan = fan.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId()).eq(ApUserFan::getUserId, author.getUserId()));
            if (apUserFan==null) saveFan(apUser,author);
            //关注行为
            HashMap<String, Object> map = new HashMap<>();
            map.put("userId",apUser.getId());
            map.put("articleId",dto.getArticleId());
            map.put("followId",author.getUserId());
            kafkaTemplate.send(BehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(map));
        }else {
            //取消关注
            follow.delete(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getUserId, apUser.getId()).eq(ApUserFollow::getFollowId, author.getUserId()));
            fan.delete(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getFansId, apUser.getId()).eq(ApUserFan::getUserId, author.getUserId()));
        }
        return successParam;
    }
    private void saveFan(ApUser apUser,ApAuthor author){
        ApUserFan userFan = new ApUserFan();
        userFan.setCreatedTime(new Date());
        userFan.setFansId(apUser.getId().longValue());
        userFan.setFansName(apUser.getName());
        userFan.setUserId(author.getUserId());
        fan.insert(userFan);
    }
    private void saveFollow(ApUser apUser,ApAuthor author){
        ApUserFollow apfollow = new ApUserFollow();
        apfollow.setCreatedTime(new Date());
        apfollow.setFollowId(author.getUserId());
        apfollow.setFollowName(author.getName());
        apfollow.setUserId(apUser.getId());
        follow.insert(apfollow);
    }
}
